package com.ppyydd.sms.studentDao;

import com.ppyydd.sms.beans.Student;
import com.ppyydd.sms.utils.JdbcUtils;

import java.sql.*;

public class IStudentDaoImpl implements IStudentDao {
    private Connection con;
    private Statement stmt;
    private PreparedStatement pstmt;
    private ResultSet rs = null;

    @Override
    public Student selectStudentByNum(String num, String password) {
        Student student = null;
        try {
            con = JdbcUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = "select * from student where num=? and password=?";
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, num);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                student = new Student();
                student.setId(rs.getInt("num"));
                student.setAge(rs.getInt("age"));
                student.setName(rs.getString("name"));
                student.setPassword(rs.getString("password"));
                student.setScore(rs.getDouble("score"));
                student.setNum(rs.getString("num"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                JdbcUtils.close(con, stmt, rs, pstmt);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return student;
    }

    @Override
    public Integer insertStudent(Student student) {
        Integer id = null;
        try {
            con = JdbcUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = "insert into student(age,score,num,password,name)values(?,?,?,?,?)";
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, student.getAge());
            pstmt.setDouble(2, student.getScore());
            pstmt.setString(3, student.getNum());
            pstmt.setString(4, student.getPassword());
            pstmt.setString(5, student.getName());
            pstmt.executeUpdate();
            sql = "SELECT @@IDENTITY newId";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                id = rs.getInt("newId");
                System.out.println(id);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                JdbcUtils.close(con, stmt, rs, pstmt);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return id;
    }
}
